﻿using System.Linq;
using System.Linq.Expressions;

namespace SimpleORM
{
    public class QueryableExpressionExpander : ExpressionVisitor
    {
        #region Methods

        #region Methods - Public

        public Expression Expand(Expression exp)
        {
            return this.Visit(exp);
        }

        #endregion

        #region Methods - Visit

        protected override Expression VisitConstant(ConstantExpression c)
        {
            IQueryable q = c.Value as IQueryable;
            if (q == null)
                return c;

            return q.Expression;
        }

        protected override Expression VisitMemberAccess(MemberExpression m)
        {
            if (!m.Type.IsKindOf(typeof(IQueryable)))
                return m;

            LambdaExpression lambda = Expression.Lambda(m);
            object obj = lambda.Compile().DynamicInvoke(null);

            IQueryable q = obj as IQueryable;
            if (q == null)
                return m;

            return q.Expression;
        }

        #endregion

        #endregion
    }
}
